package com.zufangbao.earth.handler.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.Result;
import com.demo2do.core.utils.JsonUtils;
import com.zufangbao.earth.entity.particalsystem.AppParticles;
import com.zufangbao.earth.handler.BillDepositeHandler;
import com.zufangbao.earth.service.AppParticlesService;
import com.zufangbao.earth.service.ParticalModelService;
import com.zufangbao.earth.service.ParticalService;
import com.zufangbao.gluon.api.earth.ParticleModelConfigEnum;
import com.zufangbao.gluon.api.quark.ApiSpecBillDeposite.IAssgin;
import com.zufangbao.gluon.api.quark.ApiSpecBillDeposite.ICoolingBills;
import com.zufangbao.gluon.api.quark.ApiSpecBillDeposite.IHotSnapShotAll;
import com.zufangbao.gluon.api.quark.ApiSpecBillDeposite.IRevoke;
import com.zufangbao.gluon.api.quark.ApiSpecBillDeposite.ISyncAppConfigs;
import com.zufangbao.gluon.api.quark.AppConfig;
import com.zufangbao.gluon.api.quark.AuthorisedBillSketch;
import com.zufangbao.gluon.exception.CommonException;
import com.zufangbao.gluon.spec.earth.GlobalSpec4Earth;
import com.zufangbao.gluon.spec.earth.GlobalSpec4Earth.ErrorCode4AutorisedBillSketch;
import com.zufangbao.gluon.spec.global.GlobalCodeSpec;
import com.zufangbao.gluon.spec.global.GlobalCodeSpec.GeneralErrorCode;
import com.zufangbao.gluon.spec.global.GlobalMsgSpec.GeneralErrorMsg;
import com.zufangbao.sun.entity.company.corp.App;

@Component("billDepositeHandler")
public class BillDepositeHandlerImpl implements BillDepositeHandler {
	
	public static Log logger = LogFactory.getLog(BillDepositeHandlerImpl.class);
	
	@Value("#{config['timeout']}")
	public int TIMEOUT;
	
	@Autowired
	public ParticalService particalService;
	
	@Autowired
	private ParticalModelService particalModelService;
	
	@Autowired
	private AppParticlesService appParticleService;
	
	@Override
	public boolean syncAppConfig(String uniqueParticleId, List<AppConfig> appConfigList)
			throws CommonException {
		
		if(CollectionUtils.isEmpty(appConfigList)){
			
			throw new CommonException(GlobalSpec4Earth.ERROR_ILLEGAL_PARAMS);
		}
		
		String particalModelConfigName = ParticleModelConfigEnum.CONFIG_KEY_API_SYNC_APPCONFIG.getAlias();
		
		String syncAppConfigAPIUrl = particalService.getQuarkApIUrl(uniqueParticleId, particalModelConfigName);
		
		try {
			
			logger.info("begin to assign bills with url[" + syncAppConfigAPIUrl + "]," + IAssgin.PARAM_BILLS + "["+appConfigList.toString()+"],uniqueId["+uniqueParticleId+"]");
		
			Response response = Jsoup.connect(syncAppConfigAPIUrl)
									 .method(Method.POST)
									 .data(ISyncAppConfigs.PARAM_APP_CONFIGS,JsonUtils.toJsonString(appConfigList) )
									 .timeout(TIMEOUT)
									 .execute();
			
			logger.info("get the reponse["+ response.body() + "]");
			
			Result result = JsonUtils.parse(response.body(), Result.class);
			
			logger.info("the code["+result.getCode()+"],the size [" + result.getData().get(ISyncAppConfigs.RET_SYNCED_CONFIGS)+"]");
			
			return result.getCode().equals(String.valueOf(GlobalCodeSpec.CODE_SUC));
			
		} catch (Exception e) {
			
			logger.error("sync app config error : " + e.getMessage());
			
			throw new CommonException(GeneralErrorCode.ERROR_SYSTEM);
		}
		
	}

	@Override
	public boolean assignBills(String uniqueParticalId, List<AuthorisedBillSketch> authorisedBillSketchs)
			throws CommonException {
		
		if(CollectionUtils.isEmpty(authorisedBillSketchs)){
			
			throw new CommonException(com.zufangbao.gluon.spec.earth.GlobalSpec4Earth.ErrorCode4AutorisedBillSketch.ERROR_EMPTY_AUTHORISED_BILLSKETCH);
		}
		
		String assignBillApiName = ParticleModelConfigEnum.CONFIG_KEY_API_ASSIGN_BILLS.getAlias();
		
		String assignBillApiUrl = particalService.getQuarkApIUrl(uniqueParticalId, assignBillApiName);
		
		try {
			
			logger.info("begin to assign bills with url[" + assignBillApiUrl + "]," + IAssgin.PARAM_BILLS +authorisedBillSketchs.toString());
		
			Response response = Jsoup.connect(assignBillApiUrl)
									 .method(Method.POST)
									 .data(IAssgin.PARAM_BILLS,JsonUtils.toJsonString(authorisedBillSketchs) )
									 .timeout(TIMEOUT)
									 .execute();
			
			logger.info("get the reponse["+ response.body() + "]"); 
			
			Result result = JsonUtils.parse(response.body(), Result.class);
			
			logger.info("the code["+result.getCode()+"],the size [" + result.getData().get(IAssgin.RET_ASSIGNED_BILL_COUNT)+"]");
			
			return result.getCode().equals(String.valueOf(GlobalCodeSpec.CODE_SUC));
			
		} catch (Exception e) {
			
			logger.error("assign bill error : " + e.getMessage());
			
			throw new CommonException(GeneralErrorCode.ERROR_SYSTEM);
		}
	}

	@Override
	public boolean revokeBills(String particalUniqueId, List<String> uniqueBillIds)
			throws CommonException {
		
		if(CollectionUtils.isEmpty(uniqueBillIds)){
			
			throw new CommonException(ErrorCode4AutorisedBillSketch.ERROR_EMPTY_UNIQUE_BILLIDS);
		}
		String revokeBillApiName = ParticleModelConfigEnum.CONFIG_KEY_API_REVOKE_BILLS.getAlias();
		
		String revokeBillApiUrl = particalService.getQuarkApIUrl(particalUniqueId, revokeBillApiName);
		
		
		try {
			
			logger.info("begin to revoke bills with url[" + revokeBillApiUrl + "]," + IRevoke.PARAM_BILLS + "["+uniqueBillIds.toString()+"]");
		
			Response response = Jsoup.connect(revokeBillApiUrl)
									 .method(Method.POST)
									 .data(IRevoke.PARAM_BILLS,JsonUtils.toJsonString(uniqueBillIds) )
									 .timeout(TIMEOUT)
									 .execute();
			
			logger.info("get the reponse["+ response.body() + "]");
			
			Result result = JsonUtils.parse(response.body(), Result.class);
			
			logger.info("the code["+result.getCode()+"],the size [" + result.getData().get(IRevoke.RET_REVOKED_BILL_COUNT)+"]");
			
			return result.getCode().equals(String.valueOf(GlobalCodeSpec.CODE_SUC));
			
		} catch (Exception e) {
			
			logger.error("revoke bill error : " + e.getMessage());
			
			throw new CommonException(GeneralErrorCode.ERROR_SYSTEM);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AuthorisedBillSketch> pullHotBillByApp(App app)
			throws CommonException {
		
		try {
		
			if(null == app){
				
				throw new CommonException(GlobalSpec4Earth.ERROR_NOT_EXIST_APP);
			}
			String pullHotBillApiName = ParticleModelConfigEnum.CONFIG_KEY_API_SNAPSHOT_HOT_BILLS.getAlias();
			
			String appId = app.getAppId();
			
			List<AppParticles> appParticles = appParticleService.getAppParticleByAppId(appId);
			
			List<AuthorisedBillSketch> rtnAuthorisedBillSketchs = new ArrayList<AuthorisedBillSketch>();
			
			for(AppParticles item : appParticles){
				
				String particalUniqueId  = item.getUniqueParticalId();
				
				String pullHotBillApiUrl = particalService.getQuarkApIUrl(particalUniqueId, pullHotBillApiName);
				
				
				logger.info("begin to pull hot bill with url[" + pullHotBillApiUrl+"],with "+ IHotSnapShotAll.PARAM_APPID +"[" + appId + "]");
				
				Response response = Jsoup.connect(pullHotBillApiUrl)
						.method(Method.POST)
						.data(IHotSnapShotAll.PARAM_APPID,appId)
						.timeout(TIMEOUT)
						.execute();
				
				logger.info("get the pull hot bill result[" + response.body() + "]");
				
				Result result = JsonUtils.parse(response.body(), Result.class);
				
				boolean isPullHotBillSuc = result.getCode().equals(String.valueOf(GlobalCodeSpec.CODE_SUC));
				
				if(!isPullHotBillSuc){
					
					logger.error("pull hot bills occur error,errorCode[" + result.getCode() + "]");
					
					throw new CommonException(Integer.parseInt(result.getCode()));
				}
				List<AuthorisedBillSketch> authorisedBillSketchs = JsonUtils.parseArray(result.getData().get(IHotSnapShotAll.RET_HOT_BILLS).toString(),AuthorisedBillSketch.class);
				
				logger.info("the result " + authorisedBillSketchs);
				
				rtnAuthorisedBillSketchs.addAll(authorisedBillSketchs);
			}
			return rtnAuthorisedBillSketchs;
		
		} catch (IOException e) {
			
			logger.error("pull hot bill error : " + e.getMessage());
			
			throw new CommonException(GeneralErrorCode.ERROR_SYSTEM);
		}
	}

	@Override
	public boolean coolingHotBills(List<String> uniqueBillIds, String particalUniqueId)
			throws CommonException {
		
		if(CollectionUtils.isEmpty(uniqueBillIds)){
			
			throw new CommonException(ErrorCode4AutorisedBillSketch.ERROR_EMPTY_UNIQUE_BILLIDS);
		}
		String coolingHotBillApiName = ParticleModelConfigEnum.CONFIG_KEY_API_COOLING_HOT_BILLS.getAlias();
		
		String coolingHotBillApiUrl = particalService.getQuarkApIUrl(particalUniqueId, coolingHotBillApiName);
		
		logger.info("begin to cooling hot bill with url["+ coolingHotBillApiUrl + "],with "+ ICoolingBills.PARAM_BILL_IDS + "[" + uniqueBillIds.toString() + "]");
		
		try {
			
			Response response = Jsoup.connect(coolingHotBillApiUrl)
									 .method(Method.POST)
									 .data(ICoolingBills.PARAM_BILL_IDS,JsonUtils.toJsonString(uniqueBillIds))
									 .timeout(TIMEOUT)
									 .execute();
			
			logger.info("get the cooling hot bill result[" + response.body() + "]");
			
			Result result = JsonUtils.parse(response.body(), Result.class);
			
			logger.info(ICoolingBills.RET_COOLING_BILL_COUNT + "[" + result.getData().get(ICoolingBills.RET_COOLING_BILL_COUNT)+"]");
			
			return result.getCode().equals(String.valueOf(GlobalCodeSpec.CODE_SUC));
			
		} catch (Exception e) {
			
			logger.error("cooling hot bill error : " + e.getMessage());
			
			throw new CommonException(GeneralErrorCode.ERROR_SYSTEM);
		}
	}
}
